package main

import (
	"flag"
	"fmt"
	"iron_man_comm/src/common/log"
	"iron_man_comm/src/ros_bag/cmd"
	"iron_man_comm/src/ros_bag/msg"
	"iron_man_comm/src/ros_bag/ros_bag"
	"iron_man_comm/src/ros_bag/ws"
	"time"
)

const VERSION = "1.0.1"

/**
 * @brief:    通信工具
 */
func main() {
	initLog()

	port := flag.Int("port", 9091, "ws port")

	log.Info("------------------ start run, version: %s, ws port: %d ----------------------", VERSION, *port)

	cmdCh := make(chan cmd.CmdType, 10)

	wsManager := ws.WsManager{CmdChan: &cmdCh}
	go func() {
		err := wsManager.Start(*port)
		if err != nil {
			log.Error("ws start fail, err: %s", err.Error())
			return
		}
	}()

	bagParser := ros_bag.RosBagParser{}
	for {
		select {
		case value := <-cmdCh:
			log.Info("cmdCh value: %s: %s", value.Cmd, value.Value)
			switch value.Cmd {
			case "start":
				err := bagParser.ParserBag(value.Value, func(msg msg.TopicData) {
					data := ws.ParseNotify{
						Cmd:  "parse",
						Type: "notify",
						Data: ws.ParseNotifyData{
							Topic:   msg.Topic,
							MsgType: msg.MsgType,
							Msg:     msg.Data,
						},
					}
					wsManager.SendMsg(data)
				}, func(topic string, err error) {
					log.Error("topic: %s, err: %s", topic, err.Error())
					data := ws.ParseResult{
						Cmd:  "parse",
						Type: "result",
						Data: ws.ParseResultData{
							ErrorCode: 1,
							Msg:       fmt.Sprintf("topic: %s, err: %s", topic, err.Error()),
						},
					}
					wsManager.SendMsg(data)
				})
				if err != nil {
					log.Error("parse bag fail, err: %s", err.Error())
					return
				}
				log.Info("parse done")
				data := ws.ParseResult{
					Cmd:  "parse",
					Type: "result",
					Data: ws.ParseResultData{
						ErrorCode: 0,
						Msg:       "",
					},
				}
				wsManager.SendMsg(data)
				break
			case "pause":
				bagParser.PauseParse()
				break
			case "resume":
				bagParser.ResumeParse()
				break
			case "cancel":
				bagParser.CancelParse()
				break
			default:
				log.Info("unknown cmd: %s", value.Cmd)
				break
			}
			break
		default:
			break
		}
	}
}

func initLog() {
	err := log.InitLogger(log.LogConfigs{
		LogLevel:          "debug",             // 输出日志级别 "debug" "info" "warn" "error"
		LogFormat:         "logfmt",            // 输出日志格式 logfmt, json
		LogPath:           "./log/rosbag_log/", // 输出日志文件位置
		LogFileName:       "run.log",           // 输出日志文件名称
		LogSplitTime:      time.Hour * 24,
		LogFileMaxBackups: 10,                  // 输出最大日志备份个数
		LogMaxAge:         time.Hour * 24 * 30, // 日志保留时间，单位: 天 (day)
		LogStdout:         true,                // 是否输出到控制台
	})
	if err != nil {
		fmt.Println("init log fail, error: %s", err.Error())
		return
	}
}
